from typing import Any

from sqlalchemy import Column, String, create_engine, Integer,DateTime
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

#######################################################################################################
##############初始化数据库连接，返回session
#######################################################################################################
def get_session():
    # 初始化数据库连接 # '数据库类型+数据库驱动名称://用户名:口令@机器地址:端口号/数据库名'
    engine = create_engine('mysql+pymysql://root:123456@localhost:3306/learn_goods?charset=utf8')
    DBSession = sessionmaker(bind=engine)  # 创建DBSession类型
    session = DBSession()
    # print('session:',session)
    return session
# 创建对象基类
Base = declarative_base()

####定义Goods表对象
class Goods(Base):
    # 表的名字:
    __tablename__ = 't_goods'

    # 表的结构:
    id = Column(String, primary_key=True,name='goods_id')
    goodsName = Column(String(100),name='goods_name')
    goods_price =  Column(Integer)
    goods_num = Column(Integer)
    goods_state = Column(Integer)
    creator_id = Column(String(32))
    creator_name = Column(String(100))
    updater_id = Column(String(32))
    updater_name = Column(String(100))
    create_time = Column(DateTime)
    update_time = Column(DateTime)

    def __getattribute__(self, name: str) -> Any:
        return super().__getattribute__(name)

class MyException(Exception):
    def __init__(self, ErrorInfo):
        super().__init__(self)  # 初始化父类
        self.errorinfo = ErrorInfo

    def __str__(self):
        return self.errorinfo

def selectGoodsById(goodId):
   try:
        session = get_session()
        goods = session.query(Goods).filter(Goods.id.__eq__(goodId)).one()
        session.close()
        return goods
   except Exception as e:
       print(e)
       raise MyException("查询数据库失败原因:"+e.__cause__)

goodsInfo = selectGoodsById('1316639934332796928')
print(goodsInfo.goodsName)





